﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using fuzhu;
using System.Threading;
using System.Data.SqlClient;
using Process;
using System.IO;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors.Repository;
using LKU8.shoukuan.Model;
using Newtonsoft.Json;
using ZDEntity;
 

namespace LKU8.shoukuan
{
    public partial class UC_WanJi_SCJH_Import : UserControl
    {


        //DataTable dtGongxu;
        //数据源
        BindingList<WanJi_SCJH_View> dataList = new BindingList<WanJi_SCJH_View>();
        string url;
        string chk2;
        //是否检查过数据
        Boolean bChecked = false;
        Boolean bCheckU8 = false;
        public UC_WanJi_SCJH_Import()
        {
            InitializeComponent();
      
        }

        #region 加载
      private void UserControl1_Load(object sender, EventArgs e)
        { 
             
            //重绘表格
            //gridView1.PopulateColumns();
            //绑定edit 
            //ClsGridViewBindStyle.Bind(cTable, gridView1,CanShu.conStr);
            //更新布局
            string fileName = CommonHelper.currenctDir + CanShu.cMenuname;
            if (File.Exists(fileName))
            {
                gridView1.RestoreLayoutFromXml(fileName);
            }
            
          //读取URL的信息，工时取数地址
            string sql = "select cvalue from zdy_xw_para where lx=8";

            url =DbHelper.GetDbString( DbHelper2.ExecuteScalar(sql,CanShu.conStr));

            //登陆本机电脑的时候，显示连接客户账套按钮
            if (DbHelper.GetDbString(CanShu.u8Login.cComputerName) == "WIN-20230711URG")
            {
                this.button1.Visible = true;
            }
            else
            {
                this.button1.Visible = false;
            }

            //List<InvLoopUpEntity> lstSMT = SCJH_MorderService.GetMoInvList("", CanShu.conStr);
            //repSMTLookUp.DataSource = lstSMT;
            //repSMTLookUp.ValueMember = "存货编码";
            //repSMTLookUp.DisplayMember = "存货编码";

           

        }
        #endregion

#region 增加
      public void Menu_Add()
        {
            try
            {
                //打开文件对话框
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Title = "选择生产计划Excel文件";
                ofd.Filter = "Excel files(*.xls,*.xlsx,*.xlsm)|*.xls;*.xlsx;*.xlsm|All files(*.*)|*.*";
                ofd.Multiselect = false;

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    string selectFileName = ofd.FileName;
                    
                  

                    // 获取所有工作表名称
                    List<string> sheetNames = WanJiExcelImportHelper_JH.GetSheetNames(selectFileName);
                    int selectedSheetIndex = 0;
                    
                    // 如果有多个工作表，显示选择对话框
                    if (sheetNames.Count > 1)
                    {
                        using (SheetSelectionForm sheetForm = new SheetSelectionForm(sheetNames))
                        {
                            if (sheetForm.ShowDialog(this) == DialogResult.OK)
                            {
                                selectedSheetIndex = sheetForm.SelectedSheetIndex;
                            }
                            else
                            {
                                return; // 用户取消选择
                            }
                        }
                    }

                    // 获取固定单元格位置参数
                    string dateLoc = txtDateLoc.Text.Trim();
                    string banciLoc = txtBanCiLoc.Text.Trim();
                    string headLoc = txtHeadLoc.Text.Trim();
                    
                    // 验证参数
                    if (string.IsNullOrEmpty(dateLoc)) dateLoc = "I3";
                    if (string.IsNullOrEmpty(banciLoc)) banciLoc = "K3";
                    if (string.IsNullOrEmpty(headLoc)) headLoc = "E2";

                    // 使用新的Excel导入助手导入数据
                    dataList = WanJiExcelImportHelper_JH.ImportSCJHFromExcel(selectFileName, selectedSheetIndex, dateLoc, banciLoc, headLoc);

                    // 绑定到GridControl
                    gridControl1.DataSource = dataList;
                    gridControl1.RefreshDataSource();

                    // 显示导入结果
                    string sheetInfo = sheetNames.Count > 1 ? string.Format(" (工作表: {0})", sheetNames[selectedSheetIndex]) : "";
                    MessageBox.Show(string.Format("成功导入 {0} 条记录{1}", dataList.Count, sheetInfo), "导入成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    bChecked = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导入Excel文件时发生错误：" + ex.Message, "导入失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
        #endregion

       #region 删除
      public void Menu_Del()
       {


           gridView1.PostEditor();
           gridView1.CloseEditor();
           //已录入时间的，怎么处理
           int j = 0;
           DialogResult result = CommonHelper.MsgQuestion("确认要删除已勾选行吗？");
           if (result == DialogResult.Yes)
           {
               try
               {
                   for (int i = dataList.Count - 1; i >= 0; i--)
                   {
                       if (dataList[i].chk)
                       {
                            
                          
                               dataList.RemoveAt(i);
                               j++; 
                       }
                   }
               }
               catch (Exception ex)
               {
                   //DbHelper.RollbackAndCloseConnection(tran);
                   CommonHelper.MsgError("删除失败！原因：" + ex.Message);
               }
               if (j > 0)
               {
                   CommonHelper.MsgInformation("删除完成！");
                   
               }
           }
           //Cx();
       }
       #endregion


      #region 检查已导入的数据
      public void Menu_CheckU8()
      {
          try
          {
              label1.Focus();
              gridView1.PostEditor();

              if (dataList.Count == 0)
              {

                  MessageBox.Show("请先导入表格数据");
                  return;
              }


              //查询datalist里工单号，在listU8里的数据，并设置bU8=true
              int matchedCount = 0;

              for (int i = 0; i < dataList.Count; i++)
              {
                  dataList[i].cXianbie = dataList[i].cXianbie.Replace("线", "");

                  if (SCJHService.Exists(dataList[i], CanShu.conStr))
                  {
                      dataList[i].bU8 = true;
                      matchedCount++;
                  }

              }

              //刷新数据
              gridControl1.RefreshDataSource();
              gridView1.RefreshData();

              //显示匹配结果
              MessageBox.Show(string.Format("已成功匹配 {0} 条在U8中存在的生产计划", matchedCount), "匹配完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
              bCheckU8 = true;
          }
          catch (Exception ex)
          {
              MessageBox.Show("导入Excel文件时发生错误：" + ex.Message, "导入失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
              return;
          }
      }

      #endregion

          #region 删除已导入U8的行
        /// <summary>
        /// 删除BU8= true的行
        /// </summary>
      public void Menu_DelBU8()
       {
            gridView1.PostEditor();
            gridView1.CloseEditor();
            int deleteCount = 0;
            
            // 从后往前遍历，避免删除元素后索引问题
            for (int i = dataList.Count - 1; i >= 0; i--)
            {
                if (dataList[i].bU8)
                {
                    dataList.RemoveAt(i);
                    deleteCount++;
                }
            }
            
            // 刷新数据
            gridControl1.RefreshDataSource();
            gridView1.RefreshData();
            
            // 提示删除完成
            if (deleteCount > 0)
            {
                CommonHelper.MsgInformation(string.Format("已成功删除 {0} 条已导入U8的记录", deleteCount));
            }
            else
            {
                CommonHelper.MsgInformation("没有找到已导入U8的记录");
            }
       }
       #endregion


      #region 检查数据是否完整
      /// <summary>
      /// 检查数据是否完整 - 生产计划版本
      /// </summary>
      public void Menu_CheckData()
      {
          try
          {
              //确保数据已提交
              gridView1.PostEditor();
              gridView1.CloseEditor();

              int errorCount = 0;

              for (int i = 0; i < dataList.Count; i++)
              {
                  WanJi_SCJH_View item = dataList[i];
                  string errorMsg = string.Empty;

                  //1. 检查工单号,日期,生产计划数是否输入
                  if (string.IsNullOrEmpty(item.cMocode))
                  {
                      errorMsg += "工单号不能为空；";
                  }
                  List<MomOrder_Entity> lstmo = SCJH_MorderService.GetMoList(item.cMocode, CanShu.conStr);
                  if (lstmo == null)
                  {
                      errorMsg += "工单号不存在；";
                  }
                  if (string.IsNullOrEmpty(item.cInvcode))
                  {
                      //根据机种名称读取
                      string cinv = InvService.GetInvCodeByJiZhong(item.cInvname, CanShu.conStr);
                      if (!string.IsNullOrEmpty(cinv))
                      {
                          item.cInvcode = cinv;
                      }
                      else
                      {
                          errorMsg += "根据机种查询不到编码；";
                      }
                      
                  }
                  else if (!InvService.IsInvCodeExists(item.cInvcode, CanShu.conStr))
                  {
                      errorMsg += "U8编码输入错误；";
                  }
                  //读取lstmo中 存货编码 =item.cInvcode的
                  MomOrder_Entity mo = lstmo.FirstOrDefault(x => x.InvCode == item.cInvcode);
                  if (mo == null)
                  {
                      errorMsg += "生产订单中不含这个产品；";
                  }
                  else
                  {
                      item.iModid = mo.MoDId;
                      item.iMoquantity = mo.Qty;
                  }

                  if (item.dDate == null || item.dDate == DateTime.MinValue)
                  {
                      errorMsg += "日期不能为空；";
                  }
                  if (item.iQuantity <= 0)
                  {
                      errorMsg += "生产计划数必须大于0；";
                  }
                  //去掉线字
                  if (string.IsNullOrEmpty(item.cXianbie))
                  {
                      errorMsg += "线别不能为空；";
                  }
                  else
                  {
                      item.cXianbie = item.cXianbie.Replace("线", "");
                      //读取厂区
                      WanJi_XianBie_Entity xb = SCJHService.GetXianBieEntity(item.cXianbie, CanShu.conStr);
                      if (xb == null)
                      {
                          errorMsg += "线别不存在；";
                      }
                      else if (xb.cgongxu != item.cGongxu && !string.IsNullOrEmpty(item.cGongxu))
                      {
                          //导入的工序不为空，和线别对应的不一样
                          errorMsg += string.Format("线别对应工序是{0},和导入不一致；", xb.cgongxu);
                      }
                      else if (xb.cgongxu != item.cGongxu && string.IsNullOrEmpty(item.cGongxu))
                      {
                          //导入的工序为空，取线别工序
                          item.cGongxu = xb.cgongxu;
                      }
                  }
                  if (!string.IsNullOrEmpty(item.cInvcode))
                  {
                      //读取A/B面
                      if (!item.cInvcode.StartsWith("WF") && !item.cInvcode.StartsWith("ZF") && !item.cInvcode.StartsWith("YF"))
                      {
                          //WF,ZF开头的是DIP,除去这个，除去B，都是A
                          item.AB = "A";
                      }
                      else if (item.cInvcode.StartsWith("YF"))
                      {
                          //YF开头的是B
                          item.AB = "B";
                      }
                      //，单拼点数，拼版数量 
                      zdy_wanji_pinban pinban = SCJHService.GetPinBan(item, CanShu.conStr);
                      if (pinban == null)
                      {

                          errorMsg += "产品没有定义拼版数量；";
                      }
                      else
                      {
                          item.ipbsl = pinban.ipbsl;
                          if (pinban.isczq == 0.00m)
                          {
                              errorMsg += "产品拼版档案里生产周期数是0；";
                          }

                          //预计生产时间计算
                          item.dyuji = Math.Round(DbHelper.GetDbdecimal(item.iQuantity / ((3600 / pinban.isczq) * pinban.ipbsl)), 2);


                      }
                      //读取客户名称
                      string cCusCode = SCJHService.GetCusCode(item, CanShu.conStr);
                      if (cCusCode == null)
                      {

                          errorMsg += "没有定义产品客户对照表；";
                      }
                      else
                      {
                          item.ccuscode = cCusCode;

                      }
                      
                  }
                  
                  item.cStatus = "未审核";
                  item.cMaker = CanShu.userName;
                  item.dMakedatetime = DateTime.Now;
                  //5. 如果当前行有错误，写入到【导入错误】栏目里
                  if (!string.IsNullOrEmpty(errorMsg))
                  {
                      item.cImportResult = errorMsg;
                      errorCount++;
                  }
                  else
                  {
                      item.cImportResult = "";
                  }
              }

              //刷新数据
              gridControl1.RefreshDataSource();
              gridView1.RefreshData();

              //检查完成后，设置bChecked为true，表示已经进行了数据检查
              bChecked = true;

              //检查完成后，弹窗提示
              if (errorCount > 0)
              {
                  MessageBox.Show("检查完成，发现" + errorCount + "条错误记录，请查看【导入错误】列了解详情。\n请注意：虽然已标记为已检查，但包含错误的数据将不会被导入。");
              }
              else
              {
                  MessageBox.Show("检查完成，所有数据均符合要求！");
              }
          }
          catch (Exception ex)
          {
              MessageBox.Show(ex.Message);
          }
      }
      #endregion


       public void Menu_Checkall()
       {
           if (string.IsNullOrEmpty(chk2))
           {
               for (int i = 0; i < gridView1.RowCount; i++)
               {
                   gridView1.SetRowCellValue(i, "chk", true);
                   gridView1.UpdateCurrentRow();
               }
               chk2 = "chkAll";
           }
           else
           {
               for (int i = 0; i < dataList.Count; i++)
               {
                   gridView1.SetRowCellValue(i, "chk", false);
                   gridView1.UpdateCurrentRow();
               }
               chk2 = string.Empty;
           }

           label1.Focus();
           gridView1.Focus();
       }


       #region 布局
       public void Menu_SaveBuju()
       {
           string fileName = CommonHelper.currenctDir + CanShu.cMenuname;
           gridView1.SaveLayoutToXml(fileName);
           CommonHelper.MsgInformation("保存布局成功！");

       }

       public void Menu_DelBuju()
       {


           string fileName = CommonHelper.currenctDir + CanShu.cMenuname; 
          if (File.Exists(fileName))
          {
              File.Delete(fileName);
              CommonHelper.MsgInformation("删除布局成功，请重新打开！");
          }
          else
          {
              CommonHelper.MsgInformation("布局未保存，无需删除！");
          }
         
          
       }
      
       #endregion

       #region 生成生产计划
       public void Menu_ImportMo()
       {
           try
           {
               gridView1.PostEditor();
               gridView1.UpdateCurrentRow();
               if (bCheckU8 == false)
               {
                   MessageBox.Show("请先进行导入U8匹配");
                   return;
               }
               //如果有勾选已匹配U8的，提示先删除
               var checkU8lst = dataList.Where(item => item.bU8 == true);
               if (checkU8lst.Count() > 0)
               {
                   MessageBox.Show("请先删除已导入U8数据");
                   return;
               }
               if (bChecked == false)
               {
                   MessageBox.Show("请先进行数据检查");
                   return;
               }
               checkU8lst = dataList.Where(item => !string.IsNullOrEmpty(item.cImportResult));
               if (checkU8lst.Count() > 0)
               {
                   MessageBox.Show("数据检查有错误，请先处理");
                   return;
               }
               // 生成生产计划数据推送
               WanJi_SCJH_View_Lst lst = new WanJi_SCJH_View_Lst();
               lst.vouList = new List<WanJi_SCJH_View>();
               
               int totalProcessedCount = 0;
               int totalSuccessCount = 0;
                
               // 处理每行数据
               foreach (WanJi_SCJH_View item in dataList)
               {
                   // 如果没有任何错误，才进行处理
                   if (string.IsNullOrEmpty(item.cImportResult))
                   {
                       lst.vouList.Add(item);
                       totalProcessedCount++;
                   } 
               }
              
               
               // 如果有数据需要推送
               if (lst.vouList.Count > 0)
               {
                   lst.cMaker = CanShu.userName;
                   string json = JsonConvert.SerializeObject(lst);
                   string urlfull = url + "/api/WanJi_SCJH"; // 使用生产计划API
                   string cRe = SMLWeb.PostApi("POST", urlfull, json);
                   
                   // 处理返回结果
                   RetModel2 ret = JsonConvert.DeserializeObject<RetModel2>(cRe);
                   if (ret.code == 200)
                   {
                       // 回写成功信息
                       foreach (var item in lst.vouList)
                       {
                           item.cImportResult = "导入成功：" + ret.message;
                       }
                       totalSuccessCount = lst.vouList.Count;
                   }
                   else
                   {
                       // 回写失败信息
                       foreach (var item in lst.vouList)
                       {
                           item.cImportResult = "导入失败：" + ret.message;
                       }
                   }
               }
               
               // 刷新数据
               gridControl1.RefreshDataSource();
               gridView1.RefreshData();
               
               // 显示处理结果
               MessageBox.Show(string.Format("生产计划生成完成！共处理 {0} 条记录，成功 {1} 条，失败 {2} 条。\n请查看【导入错误】列了解详情。", 
                   totalProcessedCount, totalSuccessCount, totalProcessedCount - totalSuccessCount), 
                   "处理完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
               bChecked = false;
               bCheckU8 = false;
           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.Message);
               return;
           }
       }
       #endregion

       private void gridControl1_Click(object sender, EventArgs e)
       {

       }

 



 

       #region 导出excel
       public void Menu_Excel()
       {

           SaveFileDialog saveFileDialog = new SaveFileDialog();
           saveFileDialog.Title = "导出Excel"; 
           saveFileDialog.Filter = "Excel文件(*.xls)|*.xls"; DialogResult dialogResult = saveFileDialog.ShowDialog(this);

           if (dialogResult == DialogResult.OK)
           {
               //DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();

               gridView1.OptionsPrint.AutoWidth = false;
               gridView1.ExportToXlsx(saveFileDialog.FileName);
               DevExpress.XtraEditors.XtraMessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
           }

       }
       #endregion
         



       #region 增加序号
       private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {

            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            { 
                e.Info.DisplayText = (e.RowHandle + 1).ToString(); 
            }

        }
       #endregion

       #region 序号列宽度更改
       private void gridView1_RowCountChanged(object sender, EventArgs e)
          {

              //动态设置第一列的宽度
              //string MeasureString = String.Format("{0}WA", gridView1.RowCount);
              //gridView1.IndicatorWidth = this.gridControl1.CreateGraphics().MeasureString(MeasureString, new Font("宋体", 9)).ToSize().Width;

          }
       #endregion


       #region 删除空行
       protected void RemoveEmpty(DataTable dt)
          {
              List<DataRow> removelist = new List<DataRow>();
              for (int i = 0; i < dt.Rows.Count; i++)
              {
                  bool IsNull = true;
                  for (int j = 0; j < dt.Columns.Count; j++)
                  {
                      if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
                      {
                          IsNull = false;
                      }
                  }
                  if (IsNull)
                  {
                      removelist.Add(dt.Rows[i]);
                  }
              }
              for (int i = 0; i < removelist.Count; i++)
              {
                  dt.Rows.Remove(removelist[i]);
              }
          }
       #endregion

       private void txtcPsn_Click(object sender, EventArgs e)
          {

          }

          #region 查询条件，按钮弹窗选择
        
          private void txtdept_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
          {
              e.Button.Enabled = false;
              //try
              //{

              //    DataTable dtFilter = DepService.GetDepartmentDT("", CanShu.u8Login.cUserId, CanShu.conStr, CanShu.bDepartAdmin);
              //    frm_canzhao frm = new frm_canzhao(dtFilter, this.txtdept.Text, "部门参照");
              //    frm.ShowDialog();
              //    if (frm.drxz != null)
              //    {
              //        //this.txtdept.Tag = DbHelper.GetDbString(frm.drxz["编码"]);
              //        this.txtdept.EditValue = DbHelper.GetDbString(frm.drxz["编码"]);
              //    }
              //}
              //catch (Exception EX)
              //{
              //    MessageBox.Show(EX.Message);
              //    return;
              //}
              e.Button.Enabled = true;
          }

          
          #endregion

          #region 表格内弹窗选择
          private void MOItemButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
          {
              
              //var focusedRow = gridView1.GetFocusedRow() as WanJi_Morder_Entity;
                      
              //            e.Button.Enabled = false;
              //            try
              //            {
              //                DataTable dtFilter = GetMoInfo(CanShu.conStr);
              //                frm_canzhao frm = new frm_canzhao(dtFilter, DbHelper.GetDbString(focusedRow.cMoCode), "生产订单");
              //                frm.ShowDialog();
              //                if (frm.drxz != null)
              //                {
              //                    focusedRow.cMoCode = DbHelper.GetDbString(frm.drxz["生产订单号"]);
              //                    focusedRow.cInvCode = DbHelper.GetDbString(frm.drxz["产品编码"]);  
              //                    gridView1.UpdateCurrentRow();
              //                }
              //            }
              //            catch (Exception ex)
              //            {
              //                MessageBox.Show(ex.Message);
              //            }
              //        e.Button.Enabled = true; 
          }

         
          #endregion

          private void button1_Click(object sender, EventArgs e)
          {
              //TestExcelImportForm test = new TestExcelImportForm();
              //test.Show();
          }

     

          
    }
}
